package com.senpai.database;

import java.util.LinkedList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyAnswerSQLiteHelper extends SQLiteOpenHelper{
	
	private static final int DATABASE_VERSION = 1;
	private static final String DATABASE_NAME = "Mydatabase2";

	public MyAnswerSQLiteHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);

	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String CREATE_TABLE = "CREATE TABLE answer ( "
				+ "id INTEGER PRIMARY KEY, " + "parti TEXT," + "id_answer TEXT)";

		db.execSQL(CREATE_TABLE);
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS answer");
		this.onCreate(db);
		
	}
	
	private static final String TABLE_ANSWER = "answer";
	private static final String KEY_ID = "id";
	private static final String KEY_PARTI = "parti";
	private static final String KEY_ANSWER = "id_answer";

	private static final String[] COLUMNS = { KEY_ID, KEY_PARTI,
			KEY_ANSWER};
	
	public void addAnswer(Answer answer) {
		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(KEY_ID, answer.getId());
		values.put(KEY_PARTI, answer.getParti());
		values.put(KEY_ANSWER, answer.getId_answer());
		db.insert(TABLE_ANSWER, null, values);
		db.close();
	}
	
	
	public Answer getAnswer(int id) {

		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.query(TABLE_ANSWER, COLUMNS, " id = ?",
				new String[] { String.valueOf(id) }, null, null, null, null);

		if (cursor != null)
			cursor.moveToFirst();

		Answer answer = new Answer();
		answer.setId(Integer.parseInt(cursor.getString(0)));
		answer.setParti(cursor.getString(1));
		answer.setId_answer(cursor.getString(2));

		return answer;
	}
	
	public List<Answer> getAllAnswers() {
		List<Answer> answerList = new LinkedList<Answer>();

		String query = "SELECT  * FROM " + TABLE_ANSWER;

		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.rawQuery(query, null);

		Answer answer = null;
		if (cursor.moveToFirst()) {
			do {
				answer = new Answer();
				answer.setId(Integer.parseInt(cursor.getString(0)));
				answer.setParti(cursor.getString(1));
				answer.setId_answer(cursor.getString(2));
				answerList.add(answer);
			} while (cursor.moveToNext());
		}

		return answerList;
	}


}
